package com.store.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.json.JSONObject;

import de.greenrobot.event.EventBus;

/**
 * 余额充值支付页面
 */
public class BalancePaymentActivity extends BaseActivity implements AlipayState, IOnHttpListener {


    //应付金额
    private String money;

    //充值金额
    private TextView tv_num;

    //提交
    private TextView tv_submit;
    //支付选择
    private RelativeLayout relat2, relat3;
    //支付选择imgview
    private ImageView img2, img3;
    //支付选择 1 余额 2支付宝 3微信
    private int pay_type = 2;
    //支付宝请求订单获取的model
    private AlipayModel model;
    private WXOrderbean wxOrderbean;
    private String dataStr;
    private MyReceiver myReceiver;
    private TextView title;
    private NetRequest netRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        netRequest = new NetRequest(this);
        money = getIntent().getStringExtra("money");
        setContentView(R.layout.activity_balancepayment);
        initView();
        initData();
        initListeners();
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter("FINISH"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //支付宝支付
                case 1:
                    new Alipay(BalancePaymentActivity.this, model, BalancePaymentActivity.this).pay();
//                    new Alipay(ConfirmPaymentActivity.this, bean.getTitle(), bean.getDesc1(),"0.01", model,ConfirmPaymentActivity.this).pay();
                    break;
                //余额支付成功
                case 2:
                    dismissProgressDialog();
                    Toast.makeText(BalancePaymentActivity.this, "余额充值成功！", Toast.LENGTH_LONG).show();
                    netRequest.requestQueryAccount(4);
                    EventBus.getDefault().post(new CouponGoCashBean(1));
                    finish();

                    break;
                case 3:
                    EventBus.getDefault().post(new CouponGoCashBean(2));
                    break;
                //生成微信支付订单成功，调用给微信支付
                case 4:

//                    showToast("获取订单支付信息成功："+wxOrderbean.getAppid()+"dataStr:"+dataStr);
                    Log.v("zyl", "开启微信支付");

                    if (wxOrderbean != null) {
                        WetchatPay wetchatPay = new WetchatPay(BalancePaymentActivity.this, wxOrderbean);
                        wetchatPay.pay();
//                        showToast("实体不为空：" + wetchatPay.toString());
                    }
                    break;
                case 5:
                    showToast("微信支付失败,网络波动");
                    break;

                case 9:
                    showToast("微信支付失败,网络不通");
                    break;
                case 7:
                    dismissProgressDialog();
                    showToast("网络不通，支付失败");
                    break;
                //订单支付失败
                case 8:
                    showToast(msg.obj.toString());
                    break;
            }
        }
    };

    @Override
    public void finish() {
        dismissProgressDialog();
        super.finish();
    }

    private void initListeners() {
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                } else if (pay_type == 2) {
                    //支付宝的支付方式 ZFFS_01

//                    new GetOrder(1).start();
                    netRequest.requestBalanceRecharge(3, SettingData.PAYMENT_WAY_01, money);
                } else if (pay_type == 3) {
                    //微信支付

                    boolean ifInstall = Utils.isWXAppInstalledAndSupported(BalancePaymentActivity.this);
                    if (ifInstall) {
//                        new GetOrder(2).start();
                        netRequest.requestBalanceRecharge(2, SettingData.PAYMENT_WAY_02, money);
                    } else {
                        showToast("尚未安装微信,请检查您的手机");
                        return;
                    }
                }
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        relat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 2;
                img2.setBackgroundResource(R.drawable.pay_circle);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });
        relat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 3;
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle);
            }
        });


    }

    private void initData() {

        tv_num.setText(money);
        String s_yuer = Stores.cash_balance + "";

    }

    private void initView() {
        tv_num = (TextView) findViewById(R.id.tv_money);
        tv_submit = (TextView) findViewById(R.id.submit);
        relat2 = (RelativeLayout) findViewById(R.id.pay_relat2);
        relat3 = (RelativeLayout) findViewById(R.id.pay_relat3);
        img2 = (ImageView) findViewById(R.id.pay_check_2);
        img3 = (ImageView) findViewById(R.id.pay_check_3);
        title = (TextView) findViewById(R.id.tvTitle);
        title.setText("余额充值");
    }

    @Override
    public void onAlipaySuccess() {

        handler.sendEmptyMessage(2);
    }

    @Override
    public void onAlipayFail() {
        Log.v("zyl", "支付宝支付失败");
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            handler.sendEmptyMessage(2);
        }
        //微信
        else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                Log.v("zyl", "微信生成订单成功:" + dataStr);
                wxOrderbean = new WXOrderbean();
                wxOrderbean.setTransaction_no(jsonObject.getString("transaction_no"));
                wxOrderbean.setTimestamp(jsonObject.getString("timestamp"));
                wxOrderbean.setSign(jsonObject.getString("sign"));
                wxOrderbean.setPartnerid(jsonObject.getString("partnerid"));
                wxOrderbean.setPackageX(jsonObject.getString("package"));
                wxOrderbean.setNoncestr(jsonObject.getString("noncestr"));
                wxOrderbean.setAppid(jsonObject.getString("appid"));
                wxOrderbean.setPrepayid(jsonObject.getString("prepayid"));
                handler.sendEmptyMessage(4);
            } catch (Exception e) {
            }
        }
        //支付宝
        else if (requestId == 3) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                model = new AlipayModel();
                model.setAlipay_params(jsonObject.getString("alipay_params"));
                handler.sendEmptyMessage(1);
            } catch (Exception e) {
            }
        } else if (requestId == 4) {
            try {
                Log.v("zyl","查询资产信息成功");
                JSONObject jsonObject = new JSONObject(result);
                int vo = Integer.parseInt(jsonObject.getString("voucher_balance"));
                double banlance = Double.parseDouble(jsonObject.getString("cash_balance"));
                Stores.cash_balance = banlance;
                Stores.voucher_balance = vo;
                Stores.gold = jsonObject.getString("gold");
                handler.sendEmptyMessage(3);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastUtils.showTextToast(BalancePaymentActivity.this, msg);
    }
    /**
     * 微信支付成功之后发送一个广播过来关闭页面
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            handler.sendEmptyMessage(2);
        }
    }
}
